import logging, re

from django.views import View
from django.shortcuts import render
from django.conf import settings
from django import http
from django.contrib.auth import login
from django.shortcuts import redirect
from django.urls import reverse
from django_redis import get_redis_connection
from QQLoginTool.QQtool import OAuthQQ
# Create your views here.

from oauth.models import OAuthQQUser
from meiduo_mall.utils.response_code import RETCODE
from oauth.utils import generate_eccess_token
from oauth.utils import check_eccess_token
from users.models import User
from carts.utils import merge_cart_cookie_to_redis

logger = logging.getLogger('django')


class QQAuthUserView(View):
    """处理QQ登录回调业务逻辑"""

    def get(self, request):

        # 获取code
        code = request.GET.get('code')

        # 校验是否获取到了qq返回的code
        if not code:
            return http.HttpResponseForbidden('缺少code')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)

        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('OAuth2.0认证失败')

        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # openid未绑定美多商城用户
            access_token_openid = generate_eccess_token(openid)
            context = {'access_token_openid': access_token_openid}
            return render(request, 'oauth_callback.html', context)
        else:
            # openid已绑定美多商城：oauth_user.user从表示从QQ登陆模型类对象找到对应的用户模型对象
            login(request, oauth_user.user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username', oauth_user.user.username, max_age=3600 * 24 * 15)
            return response
        return self._response(request, oauth_user.user)

    def post(self, request):

        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code_client = request.POST.get('sms_code')
        access_token_openid = request.POST.get('access_token_openid')

        if not all([mobile,pwd,sms_code_client,access_token_openid]):

            return http.HttpResponseForbidden('缺少比传参数')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
            # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', pwd):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断短信验证码是否一致

        redis_conn = get_redis_connection('verify_code')

        sms_code_server = redis_conn.get('sms_%s'%mobile)

        if sms_code_server is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg':'无效的短信验证码'})

        if sms_code_client != sms_code_server.decode():
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '输入短信验证码有误'})
        openid = check_eccess_token(access_token_openid)

        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': 'openid已失效'})
        # 与数据库对比，看电话号码是否存在，不存在则新建，存在即绑定
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(username=mobile, password=pwd, mobile=mobile)
        else:
            if not user.check_password(pwd):
                return render(request, 'oauth_callback.html', {'account_errmsg': '账号或密码错误'})
        # 用户已经存在，就将用户绑定到openid
        try:
            OAuthQQUser.objects.create(openid=openid, user=user)
        except Exception as e:
            logger.error(e)
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'QQ登录失败'})
        return self._response(request, user)

    def _response(self, request, user):
        # 保持响应状态
        login(request, user)
        # 绑定相应结果
        next = request.GET.get('state')
        response = redirect(next)

        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)
        return response


class QQAuthURLView(View):

    def get(self, requset):

        next = requset.GET.get('next')

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        login_url = oauth.get_qq_url()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})
